﻿using System.Collections.Frozen;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Apache.IoTDB;
using Apache.IoTDB.DataStructure;
using Iot.Shared.Helper;

namespace Iot.TimingDatabase.Helper;

/// <summary>
///     IoT数据库帮助类，提供与IoT数据库交互的辅助方法
/// </summary>
public static class IotDbHelp
{
    /// <summary>
    ///     存储列类型与TSDataType枚举的映射关系的只读字典
    /// </summary>
    private static readonly FrozenDictionary<string, TSDataType> ColumnTypeLst;

    /// <summary>
    ///     静态构造函数，初始化列类型映射字典
    ///     将TSDataType枚举的所有值转换为字符串（大写）作为键，对应的枚举值作为值
    /// </summary>
    static IotDbHelp()
    {
        ColumnTypeLst = EnumHelper.GetValues<TSDataType>()
            .ToFrozenDictionary(static a => a.ToString().ToUpper(), static a => a);
    }


    /// <summary>
    ///     通过不安全访问器获取SessionDataSet对象中的私有字段_columnTypeLst
    /// </summary>
    /// <param name="data">SessionDataSet对象</param>
    /// <returns>列类型字符串列表的引用</returns>
    [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_columnTypeLst")]
    private static extern ref List<string> GetColumnTypeLst(this SessionDataSet data);

    /// <summary>
    ///     获取SessionDataSet对象中所有列的数据类型
    /// </summary>
    /// <param name="data">SessionDataSet对象</param>
    /// <returns>列数据类型的枚举数组</returns>
    public static TSDataType[] GetColumnTypes(this SessionDataSet data)
    {
        // 使用映射字典将列类型字符串转换为对应的TSDataType枚举值
        // 如果找不到匹配的类型，则默认返回TSDataType.NONE
        return
        [
            .. data.GetColumnTypeLst().Select(static a => ColumnTypeLst.GetValueOrDefault(a.ToUpper(), TSDataType.NONE))
        ];
    }
}